<template>
    <div>
        <div class="tableHeadBox">
            <div class="buttonBox">
                <el-button class="addButton" type="primary" size="small" @click="ClickAdd">添加用户</el-button>
            </div>
            <div class="searchBox">
                <el-input class="searchInput" v-model="searchStr" size="small" placeholder="请输入用户"></el-input>
                <el-button class="searchButton" type="primary" size="small" :icon="Search">搜索</el-button>
            </div>
        </div>

        <!--#region 列表 -->
        <div class="tableBox">
            <el-table :data="filterTableData" height="100%" style="width: 100%">
                <el-table-column prop="id" label="ID" width="80"></el-table-column>

                <el-table-column prop="number" label="工号" width="100"></el-table-column>
                <el-table-column prop="name" label="名称" width="100"></el-table-column>
                <el-table-column prop="password" label="密码" width="100"></el-table-column>
                <el-table-column prop="phone" label="电话" width="150"></el-table-column>
                <el-table-column prop="academician" label="所属学院" width="100"></el-table-column>
                <el-table-column prop="status" label="状态" width="100">
                    <template v-slot="scope">
                        <el-tag type="success" v-if="scope.row.state">已启用</el-tag>
                        <el-tag type="info" v-else>未启用</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="role" label="角色">
                    <template v-slot="scope">
                        <el-tag v-for="(role, index) in scope.row.role" :key="index" :type="role === '超级管理员' ? 'danger' : 'warning'">{{ role }}</el-tag>
                    </template>
                </el-table-column>
                <!-- 按钮 -->
                <el-table-column fixed="right" label="操作" width="330">
                    <template #default="scope">
                        <el-button round type="warning" size="small"
                            @click="ClickEdit(scope.$index, scope.row)">编辑</el-button>
                        <el-button round type="danger" size="small"
                            @click="ClickDelete(scope.$index, scope.row)">删除</el-button>
                   
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <!-- #endregion -->
    </div>

    <!--#region 编辑 -->
    <el-dialog v-model="dialogVisible" :title="currentBuilding == null ? '添加用户' : '编辑用户'" width="500" top="30vh"
        :close-on-press-escape="false">
        <template #default="scope">
        <el-form :model="currentBuilding" label-width="100px">
          <el-form-item label="名称">
            <el-input v-model="currentBuilding.name"></el-input>
          </el-form-item>
          <el-form-item label="工号">
            <el-input v-model="currentBuilding.number"></el-input>
          </el-form-item>
          <el-form-item label="密码">
            <el-input  v-model="currentBuilding.password"></el-input>
          </el-form-item>
          <el-form-item label="电话">
            <el-input v-model="currentBuilding.phone"></el-input>
          </el-form-item>
          <el-form-item label="所属学院" prop="">
            <el-select v-model="currentBuilding.academicianId" placeholder="Select" style="width: 100%">
                <el-option v-for="item in academicianList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
        </el-form-item>
          <el-form-item label="状态">
            <el-switch v-model="currentBuilding.state"></el-switch>
          </el-form-item>
          <!-- 角色选择 -->
          <el-form-item label="角色">
                <el-checkbox-group v-model="currentBuilding.role">
                  <el-checkbox label="超级管理员" v-model="roleCheckbox.superAdmin" name="role" border></el-checkbox>
                  <el-checkbox label="实验室管理员" v-model="roleCheckbox.labAdmin" name="role" border></el-checkbox>
                  <!-- 可以根据需要添加更多角色选项 -->
                </el-checkbox-group>
              </el-form-item>
        </el-form>
        <div slot="footer">
          <el-button @click="Close">取消</el-button>
          <el-button type="primary" @click="saveUser(currentBuilding)">保存</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- #endregion -->

    <!--#region  添加-->
    <el-dialog v-model="dialogVisible1" :title=" 添加用户" width="600" top="20vh"
        :close-on-press-escape="false">
        <template #default="scope">
            <h2 style="color: black;">添加用户</h2>
        <el-form :model="currentuser" label-width="100px">
          <el-form-item label="名称">
            <el-input v-model="currentuser.name"></el-input>
          </el-form-item>
          <el-form-item label="工号">
            <el-input v-model="currentuser.number"></el-input>
          </el-form-item>
          <el-form-item label="密码">
            <el-input  v-model="currentuser.password"></el-input>
          </el-form-item>
          <el-form-item label="电话">
            <el-input v-model="currentuser.phone"></el-input>
          </el-form-item>
          <el-form-item label="所属学院" prop="">
            <el-select v-model="currentuser.academicianId" placeholder="Select" style="width: 100%">
                <el-option v-for="item in academicianList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
        </el-form-item>
          <el-form-item label="状态">
            <el-switch v-model="currentuser.state"></el-switch>
          </el-form-item>
          <!-- 角色选择 -->
          <el-form-item label="角色">
                <el-checkbox-group v-model="currentuser.role">
                  <el-checkbox label="超级管理员" v-model="roleCheckbox.superAdmin" name="role" border></el-checkbox>
                  <el-checkbox label="实验室管理员" v-model="roleCheckbox.labAdmin" name="role" border></el-checkbox>
                  <!-- 可以根据需要添加更多角色选项 -->
                </el-checkbox-group>
              </el-form-item>
        </el-form>
        <div slot="footer">
          <el-button @click="Close">取消</el-button>
          <el-button type="primary" @click="addUser()">保存</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- #endregion -->

</template>

<script setup>
import service from '@/request';
import '../assets/css/table.css'
import { Search } from '@element-plus/icons-vue'
import { onBeforeMount, reactive, ref, nextTick, watch, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import BuildingForm from '@/components/Building/BuildingForm.vue';
import BuildingMap from '@/components/Building/BuildingMap.vue';
import Three from '../components/Three/Three.vue';
// 角色复选框
const roleCheckbox = ref({
  superAdmin: false,
  labAdmin: false,
  // 可以根据需要添加更多角色选项
});

// 保存用户信息
async function saveUser() {
 
  console.log('Saving user with roles:', currentBuilding);
  await service.post("/User/updateUser",currentBuilding).then(
            async res => {
                ShowTip(true, "操作成功")
            },
            error => {
                ShowTip(false, error)
            }
        )

}

//显示提示
async function ShowTip(isSuccess, msg) {
    if (isSuccess == true) {
        ElMessage({ message: msg, type: 'success' })
    }
    else {
        ElMessage({ message: msg, type: 'error' })
    }
}


//搜索
let searchStr = ref('')
const filterTableData = computed(() =>
    tableData.filter(
        (data) =>
            !searchStr.value ||
            data.name.toLowerCase().includes(searchStr.value.toLowerCase())
    )
)


//获取数据
let tableData = reactive([])
async function getDataList() {
    let resultData = []
    await service.get("/User/getUser").then(
        (res) => {
            resultData.push(...res.value)
        }
    )
    console.log(resultData)
    return resultData
}

//获取学院数据
let academicianList = reactive([])
async function GetAcademicianData() {
    let resultData = []
    await service.get("/Mangment/getAllAcademician").then(
        (res) => {
            resultData.push(...res.value)
        }
    )
    return resultData
}
//添加/编辑
let currentBuilding = null;
let dialogVisible = ref(false)
let dialogVisible1 = ref(false)
let currentuser = reactive({
    name: '',
    number:'', 
    password: '', 
    phone: '', 
    academician: '', 
    academicianId:0,
    state: true, role: [] 
})
async function ClickAdd() {
    currentBuilding = null;
    academicianList.push(...await GetAcademicianData())
    dialogVisible1.value = true;

}
async function addUser()
{
    console.log(currentuser)
    await service.post("/User/addUser", currentuser).then(
            async res => {
                ShowTip(true, "操作成功")
            },
            error => {
                ShowTip(false, error)
            }
        )
}
async function ClickEdit(index, row) {
    currentBuilding = row;
    academicianList.push(...await GetAcademicianData())
    dialogVisible.value = true;
}
async function Close() {
    currentBuilding = null;
    dialogVisible.value = false;
    await Reload()
}




//删除
async function ClickDelete(index, row) {
    console.log(index,row)
    await ElMessageBox.confirm(
        '你确定要这么做吗，这样做将无法撤回?',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(
        async () => {
            service.delete("User/deteltUser?userId=" + row.id).then(
                async res => {
                    ShowTip(true, '删除成功')
                    await Reload()
                },
                error => {
                    ShowTip(false, '删除失败')
                }
            )
        })
        .catch(() => {
            ShowTip(false, '取消删除')
        })
}


async function Reload() {
    tableData.length = 0
    tableData.push(...await getDataList())
}

onBeforeMount(async () => {
    await Reload()
})

let dialogVisible3 = ref(false)

</script>

<style scoped>
.el-radio {
    margin-top: 10px;
    width: 250px;
}

.openMapButton {
    margin-right: 30px;
}

.buttonBox {
    float: left;
    height: 40px;
    padding-top: 10px;
    margin-left: 20px;
}

.searchInput,
.addInput {
    width: 200px;
}

.searchButton,
.addButton {
    margin-left: 10px;
}
</style>